package cs342.project1.mathNotebook.data;
import java.sql.*;

	/**
	* @author Joshua Oberle.
	*/

public class MathDatabase
{
  private String dbURL;
  private String db;
  private String pw;
  private Connection conn = null;
  private Statement state = null;

	/**
	* Creates a MathDatabase that connects to the cs342group5 database.
	*/

  public MathDatabase(){
	this("cs342group5","p9987749");
  }

	/**
	* Creates a MathDatabase that connects to the specified database.
	*
	* @param db The name of the database on the cs346 server.
	* @param pw The password for the database;
	*/

  public MathDatabase(String db, String pw)
  {
	this.dbURL = "jdbc:mysql://cs346.cs.uwosh.edu:4381/"+db;
	this.db = db;
	this.pw = pw; 
  }

	/**
	* Opens the MathDatabase for use.
	*/

  public void open(){
	try{
	      Class.forName("com.mysql.jdbc.Driver");  // register the driver
	      conn = DriverManager.getConnection(dbURL,db,pw);
	      conn.setAutoCommit(false);
	      state = conn.createStatement();
	}catch (Exception e) {e.printStackTrace();}      
  }

	/**
	* Gets the statment object associated with this Database.
	*/

  public Statement getStatement(){
	return state;
  }

	/**
	* Creates a prepared statment based on the specified string.
	*
	* @param command The base SQL command that this Prepared statment is based on.
	*/

  public PreparedStatement createPreparedStatement(String command){
	try{
		return conn.prepareStatement(command);
	}catch(Exception ex){
		ex.printStackTrace();
	}
	return null;
  }

	/**
	* Commits any changes to the Database.
	*/

  public void commit(){
	  try {
		  conn.commit();
	  }
	  catch (Exception e){
		  System.out.println("Commit problem");
	  }
  }

	/**
	* Closes the database to operations.
	*/
  
  public void close(){
	try{
	      conn.close();
	}catch (Exception e) {e.printStackTrace();} 
  }
}